package com.fingard.dsp.bank.directbank.allinpay02;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.allinpay02.util.SybUtil;
import com.fingard.dsp.bank.directbank.bankInterface.IJSAPIOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.*;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;
import com.fingard.util.DateHelper;

import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

public class AllInPay02JSAPIOrder extends AllInPay02Base implements IJSAPIOrder {
    public RetAtsUnifiedOrder submitJSAPIOrder(ReqUnifiedOrder p_req) {
        RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
            if (actItem != null) {
                String cusid = p_req.merchantId;
                if (StringHelper.isNullOrEmpty(cusid)) {
                    cusid = actItem.merchantId;
                }

                String appid = p_req.appId;
                if (StringHelper.isNullOrEmpty(appid)) {
                    appid = actItem.appId;
                }

                String payType = "";
                if ("JsWX".equalsIgnoreCase(p_req.reqHeader.commandCode)) {
                    payType = "W02";
                } else if ("JsALI".equalsIgnoreCase(p_req.reqHeader.commandCode)) {
                    payType = "A02";
                } else if ("JsQQ".equalsIgnoreCase(p_req.reqHeader.commandCode)) {
                    payType = "Q02";
                }

                // openId
                String openId = p_req.openid;
                if ("JsWX".equalsIgnoreCase(p_req.reqHeader.commandCode)) {
                    if (StringHelper.isNullOrEmpty(openId)) {
                        if (StringHelper.isNullOrEmpty(p_req.code)) {
                            retAts.respCode = "-1";
                            retAts.respInfo = "Code和Openid不能同时为空";

                            return retAts;
                        } else {
                            if (StringHelper.isNullOrEmpty(actItem.appSecret)) {
                                retAts.respCode = "-1";
                                retAts.respInfo = "未配置公众号的appsecret";

                                return retAts;
                            } else {
                                HashMap<String, String> hashOpenid = getOpenid(actItem.sellerId, actItem.appSecret, p_req.code);

                                if (hashOpenid.get("RespCode").equals("0")) {
                                    if (hashOpenid.containsKey("openid")) {
                                        openId = hashOpenid.get("openid");
                                    } else {
                                        retAts.respCode = "-1";

                                        String errcode = "";
                                        if (hashOpenid.containsKey("errcode")) {
                                            errcode = hashOpenid.get("errcode");
                                        }

                                        String errmsg = "";
                                        if (hashOpenid.containsKey("errmsg")) {
                                            errmsg = hashOpenid.get("errmsg");
                                        }

                                        retAts.respInfo = StringHelper.joinNotEmpty("-", errcode, errmsg);

                                        return retAts;
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = hashOpenid.get("RespInfo");

                                    return retAts;
                                }
                            }
                        }
                    }
                }

                String limitPay = "";
                if (StringHelper.hasAnyChar(payType)) {
                    if ("W02".equals(payType) || "A02".equals(payType)) {
                        limitPay = "no_credit";
                    }
                }

                TreeMap<String, String> params = new TreeMap<String, String>();

                params.put("cusid", cusid);
                params.put("appid", appid);
                params.put("version", "11");
                params.put("trxamt", StringHelper.amountMultiply100(p_req.amount));
                params.put("reqsn", p_req.rdSeq);
                params.put("paytype", payType); /* 交易方式 (W02-微信JS支付, A02-支付宝JS支付, A02-支付宝JS支付) */
                params.put("randomstr", get_nonce_str());
                params.put("body", XmlHelper.encode(p_req.description));
                String attach = new StringBuilder(p_req.attach).substring(0, 50);
                params.put("remark", attach);
                params.put("validtime", p_req.getValidTime());
                if ("JsALI".equalsIgnoreCase(p_req.reqHeader.commandCode)) {
                    params.put("acct", p_req.alipayUid);
                } else {
                    params.put("acct", openId);
                }
                params.put("notify_url", actItem.notifyURL);
                params.put("limit_pay", limitPay); /* 暂时只对微信支付和支付宝有效,仅支持no_credit */
                if ("JsWX".equalsIgnoreCase(p_req.reqHeader.commandCode)) {
                    params.put("sub_appid", actItem.sellerId);
                }
                params.put("sign", SybUtil.sign(params, actItem.saltKey));

                String tmpRetStr = sendUnifiedToBank(params, bankFront.getUrl("unifiedOrderSubmit"));

                if (StringHelper.hasAnyChar(tmpRetStr)) {
                    if (tmpRetStr.indexOf("{") >= 0) {
                        JSONObject respJson = JSONObject.parseObject(tmpRetStr);

                        String respCode = respJson.getString("retcode");
                        if ("SUCCESS".equals(respCode)) {
                            retAts.respCode = "0";
                            retAts.rdSeq = respJson.getString("reqsn");
                            retAts.transState = respCode + "+" + respJson.getString("trxstatus");
                            retAts.payInfoCode = respJson.getString("trxstatus");
                            retAts.respInfo = respJson.getString("retmsg");
                            String errMsg = respJson.getString("errmsg");
                            if (StringHelper.hasAnyChar(errMsg)) {
                                retAts.respInfo = errMsg;
                            }
                            if ("JsWX".equalsIgnoreCase(p_req.reqHeader.commandCode)) {
                                String payInfoStr = respJson.getString("payinfo");
                                JSONObject payInfoJson = JSONObject.parseObject(payInfoStr);
                                retAts.customHashMap = new HashMap<String, String>();
                                retAts.customHashMap.put("timeStamp", payInfoJson.getString("timeStamp"));
                                retAts.customHashMap.put("package", payInfoJson.getString("package"));
                                retAts.customHashMap.put("appId", payInfoJson.getString("appId"));
                                retAts.customHashMap.put("signType", payInfoJson.getString("signType"));
                                retAts.customHashMap.put("nonceStr", payInfoJson.getString("nonceStr"));
                                retAts.customHashMap.put("paySign", payInfoJson.getString("paySign"));
                            } else {
                                retAts.payInfo = respJson.getString("payinfo");
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = respJson.getString("retmsg");
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetStr;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "通联响应数据为空";
                }
            } else {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
    }

    public RetAtsQueryOrder queryJSAPIPay(ReqQueryOrder p_req) {
        RetAtsQueryOrder retAts = new RetAtsQueryOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
            if (actItem != null) {
                TreeMap<String, String> params = new TreeMap<String, String>();

                String cusid = p_req.merchantId;
                if (StringHelper.isNullOrEmpty(cusid)) {
                    cusid = actItem.merchantId;
                }

                String appid = p_req.appId;
                if (StringHelper.isNullOrEmpty(appid)) {
                    appid = actItem.appId;
                }

                params.put("cusid", cusid);
                params.put("appid", appid);
                params.put("version", "11");
                params.put("reqsn", p_req.rdSeq);
                params.put("trxid", "");
                params.put("randomstr", get_nonce_str());
                params.put("sign", SybUtil.sign(params, actItem.saltKey));

                String tmpRetStr = sendUnifiedToBank(params, bankFront.getUrl("unifiedOrderQuery"));

                if (StringHelper.hasAnyChar(tmpRetStr)) {
                    if (tmpRetStr.indexOf("{") >= 0) {
                        JSONObject respJson = JSONObject.parseObject(tmpRetStr);

                        String respCode = respJson.getString("retcode");
                        if ("SUCCESS".equals(respCode)) {
                            retAts.respCode = "0";
                            retAts.respInfo = respJson.getString("retmsg");
                            retAts.rdSeq = respJson.getString("reqsn");
                            retAts.outTransID = respJson.getString("chnltrxid"); /* 如支付宝,微信平台的交易单号 */
                            retAts.transState = StringHelper.joinNotEmpty("+", respCode, respJson.getString("trxstatus"));
                            retAts.payInfoCode = respJson.getString("errmsg");
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = respJson.getString("retmsg");
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetStr;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "通联响应数据为空";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
    }

    public RetAtsGenGetUserCodeURL GenGetUserCodeURL(ReqGenGetUserCodeURL p_req) {
        RetAtsGenGetUserCodeURL retAts = new RetAtsGenGetUserCodeURL();

        retAts.respCode = "0";
        retAts.respInfo = "未实现该接口";

        return retAts;
    }

    @Override
    public RetAtsGenGetUserCodeURL getUserId(ReqGenGetUserCodeURL p_req) {
        return null;
    }

    @Override
    public RetAtsGenRealNameURL genRealNameURL(ReqGenRealNameURL p_req) {
        // TODO Auto-generated method stub
        return null;
    }
}
